<template>
  <div class="Market">
    <div class="main">
      <div class="flex mb">
        <!-- 操作交易对 -->
        <div class="mr changeCaption">{{$t('swap.s64')}}</div>
        <el-select v-model="checked.pair_id"
        @change="handleSymbelChecke(checked.pair_id)"
        slot="prepend" :placeholder="$t('swap.s61')" class="selectClass">
          <div class="slotClass flex" slot="prefix">
            <img class="checkAreaImg" :src="handleLogo(checked)" alt=""/>
          </div>
          <template v-for="(item, index) in symbolList">
            <el-option
              :label="item.symbol"
              :value="item.pair_id"
              :key="index">
              <div class="slotClass flex">
                <img class="checkAreaImg" :src="handleLogo(item)" v-if="handleLogo(item)" alt=""/>
                <span>{{ item.symbol }}</span>
              </div>
            </el-option>
          </template>
        </el-select>
      </div>
      <div class="cont flex">
        <div class="contLeft flex">
          <div class="leftItem">
            <!-- 存入资产 -->
            <div class="mb">{{ $t('swap.s41') }}</div>
            <!-- 凭证数量 -->
            <div class="canRetrieve" style="margin-top: 160px;">{{ $t('swap.s34') }}</div>
          </div>
          <!-- 存入资产 -->
          <div class="rightItem">
            <el-input :placeholder="$t('swap.s65')"
              type="number"
              clearable
              v-model="checked.pay"
              @input="handlePayNumberInput"
              @blur="handleNumberBlur(2)">
              <template slot="prepend">
                <div class="slotCls flex">
                  <img :src="checked.symbol2_logo" alt="">
                  <span>{{checked.symbol2}}</span>
                </div>
              </template>
            </el-input>
            <div class="mt5 mb5"
              v-if="scatter && scatter.identity
              && scatter.chain === 'eos'">
              <div class="flexb balance">
                <span></span>
                <!-- 可用余额 -->
                <span
                  @click="checked.pay=checked.symbol2_balance;handlePayNumberInput()">{{ $t('swap.s16') }}：
                  <span v-if="checked.symbol2_balance !== null">{{checked.symbol2_balance}}</span>
                  <i v-else class="el-icon-refresh el-icon-loading"></i>
                  {{checked.symbol2}}
                </span>
              </div>
            </div>
            <div class="mt5 mb5" v-else>&nbsp;</div>
            <el-input :placeholder="$t('swap.s65')"
              v-model="checked.get"
              type="number"
              clearable
              @blur="handleNumberBlur(1)"
              @input="handleGetNumberInput">
              <template slot="prepend">
                <div class="slotCls flex">
                  <img :src="checked.symbol1_logo" alt="">
                  <span>{{checked.symbol1}}</span>
                </div>
              </template>
            </el-input>
            <!-- 最小存币额度需大于{{maxPayEosNumber}}EOS -->
            <div class="errorCodexPay" style="padding:3px 0 0 70px; font-size:12px; color:#f00"
              v-if="errorCodexPay">
              {{ $t('swap.s66', {num:maxPayEosNumber}) }}
            </div>
            <div class="mt5 mb5"
              v-if="scatter && scatter.identity
              && scatter.chain === 'eos'">
              <div class="flexb balance">
                <span></span>
                <!-- 可用余额： -->
                <span
                  @click="checked.get=checked.symbol1_balance;handleGetNumberInput()">{{ $t('swap.s16') }}：
                  <span v-if="checked.symbol1_balance !== null">{{checked.symbol1_balance}}</span>
                  <i v-else class="el-icon-refresh el-icon-loading"></i>
                  {{checked.symbol1}}
                </span>
              </div>
            </div>
            <div class="mt5 mb5" v-else>&nbsp;</div>
            <div class="jt" style="margin: 13px auto 13px;">
              <div class="iconOuter">
                <i class="iconfont icon-huaban124"></i>
              </div>
            </div>
            <!-- 预计获得凭证数量 -->
            <el-input :placeholder="$t('swap.s58')"
              v-model="userCodex.ygToken"
              type="number"
              disabled>
            </el-input>
            <!-- <div>预估Token: {{userCodex.ygToken}}</div> -->
            <div>
              <!-- 免费cpu -->
              <div v-if="scatter && scatter.identity
                && scatter.chain === 'eos'"
                style="margin-top: 20px;">
                <div class="freeCpu flex" :style="$store.state.app.language === 'en' ? 'line-height: 15px;' : 'line-height: 10px;'">
                  <el-checkbox v-model="freeCpuChecked"
                    :style="$store.state.app.language === 'en' ? 'margin-top: -2px;' :''"
                    :disabled="userInfo && !userInfo.remainFreeOrderCount">
                    <free-cpu :user="userInfo" :embed="embed"/>
                  </el-checkbox>
                </div>
              </div>
              <div v-else style="margin-top: 20px;">&nbsp;</div>
              <!-- 免费cpu end-->
              <!-- 存币 -->
              <el-button
              v-if="scatter && scatter.chain === 'eos' && scatter.identity"
              type="primary"
              class="btn btn-color-green"
              @click="handlePaySubmit"
              v-loading="chuLoading">
                {{ $t('swap.s14') }}
              </el-button>
              <el-button type="primary" class="btn" @click="handleWalletPermission('EOS')" v-else>
                {{ $t('swap.s98') }}
              </el-button>
            </div>
          </div>
        </div>
        <div class="contRight flex">
          <div class="leftItem">
            <!-- 取回资产 -->
            <div class="mb">{{ $t('swap.s42') }}</div>
            <!-- 可取回资产 -->
            <div class="canRetrieve">{{ $t('swap.s21') }}</div>
          </div>
          <div class="rightItem">
            <!-- 请输入取出凭证数量 -->
            <el-input :placeholder="$t('swap.s59')" v-model="quNumber"
            type="number"
            clearable
            v-Int
            @input="handleCodexQuInput"></el-input>
            <div class="flexb balance mt"
              v-if="scatter && scatter.identity
              && scatter.chain === 'eos'">
              <span></span>
              <!-- 凭证余额 -->
              <span @click="quNumber = Number(userCodex.token);handleCodexQuInput()">{{ $t('swap.s53') }}：{{userCodex.token}} </span>
            </div>
            <div v-else class="flexb balance mt">&nbsp;</div>
            <div class="jt" style="margin: 12px auto 12px;">
              <div class="iconOuter">
                <i class="iconfont icon-huaban124"></i>
              </div>
            </div>
            <div>
              <div style="margin-bottom: 20px;">
                <div>
                  <el-input disabled v-model="userCodex.quSymbol2">
                    <template slot="prepend">
                      <div class="slotCls flex">
                        <img :src="checked.symbol2_logo" alt="">
                        <span>{{checked.symbol2}}</span>
                      </div>
                    </template>
                  </el-input>
                </div>
              </div>
              <div>
                <el-input disabled v-model="userCodex.quSymbol1">
                  <template slot="prepend">
                    <div class="slotCls flex">
                      <img :src="checked.symbol1_logo" alt="">
                      <span>{{checked.symbol1}}</span>
                    </div>
                  </template>
                </el-input>
              </div>
            </div>
            <div>
              <!-- 免费cpu -->
              <div v-if="scatter && scatter.identity
                && scatter.chain === 'eos'
                && scatter.by !== 'mobileWallet'"
                style="margin-top: 20px;">
                <div class="freeCpu flex" :style="$store.state.app.language === 'en' ? 'line-height: 15px;' : 'line-height: 10px;'">
                  <el-checkbox v-model="freeCpuChecked"
                    :style="$store.state.app.language === 'en' ? 'margin-top: -2px;' :''"
                    :disabled="userInfo && !userInfo.remainFreeOrderCount">
                    <free-cpu :user="userInfo" :embed="embed"/>
                  </el-checkbox>
                </div>
              </div>
              <div v-else style="margin-top: 20px;">&nbsp;</div>
              <!-- 免费cpu end-->
              <!-- 取回 -->
              <el-button
              v-if="scatter && scatter.chain === 'eos' && scatter.identity"
              type="primary"
              style="margin-top: 14px;"
              class="btn btn-color-red"
              @click="handleQuSubmit"
              v-loading="quLoading">
                {{ $t('swap.s23') }}
              </el-button>
              <el-button type="primary"
              style="margin-top: 14px;"
              class="btn" @click="handleWalletPermission('EOS')" v-else>
                {{ $t('swap.s98') }}
              </el-button>
            </div>
          </div>
        </div>
        <span class="centIcon">
        </span>
      </div>
      <div class="nowPrice flexb pl pr">
        <!-- <div>
          {{checked.symbol1}}/{{checked.symbol2}}
        </div> -->
        <!-- 兑换比例： -->
        <div class="ml nowPriceItem">
          <div>{{ $t('swap.s17') }}</div>
          <div>1 {{checked.quote.coin}} = {{checked.bqPrice}} {{checked.base.coin}}</div>
        </div>
        <!-- 池内存币数据： -->
        <div class="ml nowPriceItem">
          <div>{{ $t('swap.s18') }}</div>
          <div>
            <span>{{checked.quote_quantity}}</span>
            <span style="padding-left: 20px">{{checked.base_quantity}}</span>
          </div>
        </div>
        <!-- 我的做市商池 -->
        <div class="ml nowPriceItem">
          <div>{{ $t('swap.s19') }}（{{userCodex.bili}}%）</div>
          <div>
            <span>{{userCodex.quote_quantity}}</span>
            <span style="padding-left: 20px">{{userCodex.base_quantity}}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 温馨提示 服务暂停-->
    <div v-if="stopSwap">
      <tips
        :text="stopSwapType ? `${$t('swap.s104')}` : $t('swap.s54')"
        :width="400"
        :showBtn = true
        @listenTips="(() => {stopSwap=false})" />
    </div>
  </div>
</template>

<script>
import { bitModel } from '@/utils/eos/bitpeicurrex';
import FreeCpu from '@/components/FreeCpu';
import Tips from '@/components/Tips'; // 弹出提示
// accAdd、accSub、accMul、accDiv
import { toFixed, accAdd, accSub, accMul, accDiv, getTargetOrigin } from '@/utils/validate';
import Bus from '@/utils/bus';

export default {
  name: 'Market', // 做市商
  data() {
    return {
      chuLoading: false,
      quLoading: false,
      checked: {
        pair_id: null,
        symbol1_balance: null,
        symbol2_balance: null,
        pay: null,
        get: null,
        quote: {},
        base: {}
      },
      errorCodexPay: false, // 错误提示
      maxPayEosNumber: 1,
      errorCodexGet: false,
      userCodex: { // 用户取回各个币数量
        quSymbol1: null,
        quSymbol2: null, // 取出凭证数量 EOS
        ygToken: null, // 预估凭证
      },
      quNumber: null, // 取出凭证数量
      freeCpuChecked: false,
      userInfo: {},
      stopSwap: false, // 服务暂停
      stopSwapType: 0, // 0-服务暂停 1-单个币种暂停
    }
  },
  components: {
    FreeCpu,
    Tips,
  },
  props: {
    symbolList: Array,
    scatter: Object,
    symbolScience: String,
    user: Object,
    statusObj: Object,
    embed: {
      type: Boolean,
      default: false
    },
    symbolChecked: Object
  },
  watch: {
    symbolList: function change(val) {
      let pairId = this.checked.pair_id || val[0].pair_id;
      if (this.symbolChecked && this.symbolChecked.symbol) {
        const index = this.symbolList.findIndex(v => v.symbol === this.symbolChecked.symbol);
        if (index !== -1 && this.embed) {
          pairId = this.symbolList[index].pair_id;
        }
      }
      this.handleSymbelChecke(pairId);
    },
    '$store.state.app.scatter.identity': {
      handler: function listen(val) {
        this.handleDataFormat();
        if (!val) return;
        // 选择交易对
        if (this.symbolList && this.symbolList.length > 0) {
          this.handleSymbelChecke(this.symbolList[0].pair_id);
        }
        this.handleBlanceIvit(1);
        this.handleBlanceIvit(2);
        // 获取用户codex资产信息
        this.handleGetCodexUserSymbel();
      },
      deep: true,
    },
    'checked.pair_id': function change() {
      // this.$emit('listenCodex', 'getSymbol', { pairId: val });
      this.$emit('listenCodex', 'getSysbolInfo');
      this.handleDataFormat();
      // 获取用户codex资产信息
      this.handleGetCodexUserSymbel();
      this.handleBlanceIvit(1);
      this.handleBlanceIvit(2);
    },
    // 监听账户等级变化
    user: {
      handler: function listen(val) {
        this.userInfo = val;
        if (this.userInfo && this.userInfo.remainFreeOrderCount === 0) {
          this.freeCpuChecked = false;
        }
      },
      deep: true,
    },
  },
  computed: {},
  created() {},
  mounted() {
    this.userInfo = this.user;
    // 选择交易对
    if (this.symbolList && this.symbolList.length > 0) {
      let pairId = this.symbolList[0].pair_id;
      let index = this.symbolList.findIndex(v => v.symbol === 'USN/EOS');
      if (index !== -1 && this.embed) {
        pairId = this.symbolList[index].pair_id;
      }
      if (this.symbolChecked && this.symbolChecked.symbol) {
        index = this.symbolList.findIndex(v => v.symbol === this.symbolChecked.symbol);
        if (index !== -1) {
          pairId = this.symbolList[index].pair_id;
        }
      }
      this.handleSymbelChecke(pairId);
    }
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleReceiveMessage, false);
  },
  methods: {
    // 存币操作
    async handlePaySubmit() {
      const pay = Number(this.checked.pay || 0);
      const get = Number(this.checked.get || 0);
      // 当池子无token时
      if (pay <= 0) {
        this.$message.error(this.$t('swap.s68', { code: this.checked.symbol2 }));
        return;
      }
      // 当池子无token时
      if (get <= 0) {
        this.$message.error(this.$t('swap.s68', { code: this.checked.symbol1 }));
        return;
      }
      // 余额不足
      if (parseFloat(this.checked.symbol2_balance) < this.checked.pay) {
        this.$message.error(this.$t('swap.s69', { code: this.checked.symbol2 }));
        return;
      }
      if (parseFloat(this.checked.symbol1_balance) < get) {
        this.$message.error(this.$t('swap.s69', { code: this.checked.symbol1 }));
        return;
      }
      // 存币最小额度
      // if (pay < this.maxPayEosNumber) {
      //   this.errorCodexPay = true;
      //   return;
      // }

      if (this.chuLoading) return;
      this.chuLoading = true;
      const status = await this.handleServerStatus({});
      // 优先判断服务状态
      if (status === 0) {
        this.stopSwapType = 0;
        this.stopSwap = true;
        this.chuLoading = false;
        return;
      }
      let symbolStatus = 1;
      if (status === 1) {
        const obj = { symbolStatus: 1 }
        symbolStatus = await this.handleServerStatus(obj);
      }
      // 判断币种状态
      if (symbolStatus === 0) {
        this.stopSwapType = 1;
        this.stopSwap = true;
        this.chuLoading = false;
        return;
      }
      if (this.scatter.by === 'mobileWallet') {
        this.$emit('listenCodex', 'walletByPhone');
        this.chuLoading = false;
        return;
      }
      this.checked.symbol2_quantity = `${toFixed(Number(this.checked.pay), this.checked.symbol2_decimal)} ${this.checked.symbol2}`;
      this.checked.symbol1_quantity = `${toFixed(Number(this.checked.get), this.checked.symbol1_decimal)} ${this.checked.symbol1}`;
      this.checked.freeCpu = this.freeCpuChecked;

      if (this.embed) { // 如果是内嵌
        window.removeEventListener('message', this.handleReceiveMessage, false);
        window.addEventListener('message', this.handleReceiveMessage, false);
        const targetOrigin = getTargetOrigin();
        const accountItem = this.$store.state.app.scatter.identity.accounts[0];
        const formName = accountItem.name;
        const permission = accountItem.authority;
        const obj = this.checked;
        const dataItem = {
          actions: [
            {
              account: obj.symbol2_code,
              name: 'transfer',
              authorization: [{
                actor: formName, // 转账者
                permission,
              }],
              data: {
                from: formName,
                to: 'swap.newdex',
                quantity: obj.symbol2_quantity,
                memo: `deposit-${obj.pair_id}`
              }
            },
            {
              account: obj.symbol1_code,
              name: 'transfer',
              authorization: [{
                actor: formName, // 转账者
                permission,
              }],
              data: {
                from: formName,
                to: 'swap.newdex',
                quantity: obj.symbol1_quantity,
                memo: `deposit-${obj.pair_id}`
              }
            }
          ]
        };
        const postParams = {
          action: 'eosTransaction',
          data: dataItem,
          useFreeCpu: obj.freeCpu
        }
        window.parent.postMessage(JSON.stringify(postParams), targetOrigin);
        return;
      }
      bitModel.depositTransfer(this.checked, (res) => {
        this.chuLoading = false;
        if (res && (res.broadcast || res.processed)) {
          this.handleDataFormat();
          this.$emit('listenCodex', 'getSysbolInfo');
          if (this.freeCpuChecked) {
            this.$emit('listenCodex', 'getAccountInfo');
          }
          // 获取用户codex资产信息
          setTimeout(() => {
            this.handleChange();
            this.handleGetCodexUserSymbel();
            this.handleBlanceIvit(1);
            this.handleBlanceIvit(2);
          }, 2000);
          this.$message.success(this.$t('newpos.successfulOperation'));
          return
        }
        bitModel.handleScatterErrorBack(res)
      })
    },
    // 取回操作
    async handleQuSubmit() {
      // 余额不足
      if (!this.userCodex.token || this.quNumber > this.userCodex.token) {
        this.$message.error(this.$t('jy.error3'));
        return;
      }
      // 请输入有效的凭证数量
      if (this.quNumber <= 0) {
        this.$message.error(this.$t('swap.s70'));
        return;
      }

      if (this.quLoading) return;
      this.quLoading = true;

      const status = await this.handleServerStatus({});
      // 优先判断服务状态
      if (status === 0) {
        this.stopSwapType = 0;
        this.stopSwap = true;
        this.quLoading = false;
        return;
      }
      let symbolStatus = 1;
      if (status === 1) {
        const obj = { symbolStatus: 1 }
        symbolStatus = await this.handleServerStatus(obj);
      }
      // 判断币种状态
      if (symbolStatus === 0) {
        this.stopSwapType = 1;
        this.stopSwap = true;
        this.quLoading = false;
        return;
      }
      if (this.scatter.by === 'mobileWallet') {
        this.$emit('listenCodex', 'walletByPhone');
        this.quLoading = false;
        return;
      }
      this.userCodex.quNumber = Number(this.quNumber);
      this.userCodex.freeCpu = this.freeCpuChecked;
      this.quLoading = true;

      if (this.embed) { // 如果是内嵌
        window.removeEventListener('message', this.handleReceiveMessage, false);
        window.addEventListener('message', this.handleReceiveMessage, false);
        const targetOrigin = getTargetOrigin();
        const accountItem = this.$store.state.app.scatter.identity.accounts[0];
        const formName = accountItem.name;
        const permission = accountItem.authority;
        const obj = this.userCodex;
        const dataItem = {
          actions: [
            {
              account: 'swap.newdex',
              name: 'withdraw',
              authorization: [{
                actor: formName, // 转账者
                permission,
              }],
              data: {
                pair_id: obj.pair_id,
                owner: obj.owner,
                token: obj.quNumber
              }
            },
          ]
        };
        const postParams = {
          action: 'eosTransaction',
          data: dataItem,
          useFreeCpu: obj.freeCpu
        }
        window.parent.postMessage(JSON.stringify(postParams), targetOrigin);
        return;
      }

      bitModel.withdraw(this.userCodex, (res) => {
        this.quLoading = false;
        if (res && (res.broadcast || res.processed)) {
          this.handleDataFormat();
          this.$emit('listenCodex', 'getSysbolInfo');
          if (this.freeCpuChecked) {
            this.$emit('listenCodex', 'getAccountInfo');
          }
          setTimeout(() => {
            this.handleChange();
            // 获取用户codex资产信息
            this.handleGetCodexUserSymbel();
            this.handleBlanceIvit(1);
            this.handleBlanceIvit(2);
          }, 2000);
          this.$message.success(this.$t('newpos.successfulOperation'));
          return
        }
        bitModel.handleScatterErrorBack(res)
      })
    },
    // 嵌入交易代码 addEventListener message callback
    handleReceiveMessage(event) {
      // 这里不准确，chrome没有这个属性
      const origin = event.origin || event.originalEvent.origin;
      if (origin === window.location.origin) return;
      const message = JSON.parse(event.data);
      switch (message.action) {
        case 'eosTransaction': {
          const res = message.data.res;
          this.chuLoading = false;
          this.quLoading = false;
          if (res && (res.broadcast || res.processed)) {
            this.handleDataFormat();
            this.$emit('listenCodex', 'getSysbolInfo');
            if (this.freeCpuChecked) {
              this.$emit('listenCodex', 'getAccountInfo');
            }
            setTimeout(() => {
              this.handleChange();
              // 获取用户codex资产信息
              this.handleGetCodexUserSymbel();
              this.handleBlanceIvit(1);
              this.handleBlanceIvit(2);
            }, 2000);
            this.$message.success(this.$t('newpos.successfulOperation'));
          }
          break;
        }
        default:
      }
    },
    // 选择交易对
    handleSymbelChecke(id) {
      const listString = JSON.stringify(this.symbolList);
      const list = JSON.parse(listString);
      const item = list.find(v => v.pair_id === id);
      if (item) {
        item.symbol1_balance = this.checked.symbol1_balance;
        item.symbol2_balance = this.checked.symbol2_balance;
        item.pay = this.checked.pay;
        item.get = this.checked.get;
        this.checked = item;
      }
    },
    // 获取用户codex资产信息
    handleGetCodexUserSymbel() {
      const params = {
        pair_id: this.checked.pair_id,
        symbol1: this.checked.symbol1,
        symbol2: this.checked.symbol2
      }
      bitModel.getCodexUserSymbel(params, (res) => {
        this.userCodex = res;
        this.userCodex.bili = toFixed(accDiv(this.userCodex.token, this.checked.token) * 100, 2);
      })
    },
    // 取出凭证数量输入
    handleCodexQuInput() {
      if (!this.userCodex.token) return;
      const num = this.quNumber;
      const zb = accDiv(num, parseFloat(this.checked.token)); // 占比 = token / 池子总token
      this.userCodex.quSymbol1 = toFixed(accMul(parseFloat(this.checked.base_quantity), zb) * 1, this.checked.symbol1_decimal);
      this.userCodex.quSymbol2 = toFixed(accMul(parseFloat(this.checked.quote_quantity), zb) * 1, this.checked.symbol2_decimal);
      this.$forceUpdate();
    },
    // 余额获取
    handleBlanceIvit(n) {
      const scatter = this.scatter;
      if (scatter && scatter.identity && scatter.chain === 'eos') {
        let coin = this.checked[`symbol${n}`];
        if (coin === 'EOS') {
          coin = this.symbolScience;
        }
        bitModel.EosModel.getCurrencyBalance(coin, this.checked[`symbol${n}_code`], (result) => {
          if (result.error) return;
          let res = result;
          if (!res) return;
          if (res.length === 0) {
            res = 0;
          } else {
            res = result[0];
          }
          this.checked[`symbol${n}_balance`] = toFixed(parseFloat(res, 0) || 0, this.checked[`symbol${n}_decimal`]);
          this.$forceUpdate(); // 强制更新
        });
        return;
      }
      this.checked[`symbol${n}_balance`] = toFixed(0, this.checked[`symbol${n}_decimal`]);
      this.$forceUpdate(); // 强制更新
    },
    // 支付额度输入
    handlePayNumberInput() {
      this.errorCodexPay = false;
      const pay = this.checked.pay;
      if (parseFloat(this.checked.token)) {
        this.checked.get = accMul(pay, Number(this.checked.bqPrice)) * 1;
      }
      this.handleGetYuGuToken();
      this.$forceUpdate(); // 强制更新
    },
    // 得到额度输入
    handleGetNumberInput() {
      this.errorCodexPay = false;
      const get = this.checked.get;
      if (parseFloat(this.checked.token)) {
        this.checked.pay = accDiv(get, Number(this.checked.bqPrice)) * 1;
      }
      this.handleGetYuGuToken();
      this.$forceUpdate(); // 强制更新
    },
    // 得到预估凭证 tokne
    handleGetYuGuToken() {
      // 计算公式
      // ratio = EOS / (EOS + pool EOS);
      // ygToken = ratio * pool Token / (1.0 - ratio);
      // accAdd、accSub、accMul、accDiv
      const pay = parseFloat(this.checked.pay);
      if (!pay) {
        this.userCodex.ygToken = null;
        return;
      }
      if (parseFloat(this.checked.token)) {
        const all = accAdd(pay, parseFloat(this.checked.quote_quantity));
        const paybli = accDiv(pay, all);
        const ygToken = accMul(paybli, this.checked.token);
        const onejian = accSub(1, paybli);
        const token = accDiv(ygToken, onejian);
        this.userCodex.ygToken = parseInt(token, 0);
        return;
      }
      this.userCodex.ygToken = pay * 10000;
    },
    // 格式化数字精度
    handleNumberBlur(n) {
      if (parseFloat(this.checked.token)) {
        const decimal = this.checked[`symbol${n}_decimal`];
        if (n === 2) {
          this.checked.pay = toFixed(this.checked.pay, decimal);
          const d = this.checked.symbol1_decimal;
          this.checked.get = toFixed(this.checked.get, d);
        } else {
          this.checked.get = toFixed(this.checked.get, decimal);
          const d = this.checked.symbol2_decimal;
          this.checked.pay = toFixed(this.checked.pay, d);
        }
        this.$forceUpdate();
      }
    },
    handleDataFormat() {
      this.checked.pay = null;
      this.checked.get = null;
      this.userCodex = { // 用户取回各个币数量
        quSymbol1: null,
        quSymbol2: null, // 取出凭证数量 EOS
        ygToken: null,
      };
      this.quNumber = null; // 取出凭证数量
      this.errorCodexPay = false;
      this.errorCodexGet = false;
    },
    // 登录授权
    handleWalletPermission(bychain) {
      const checkWallet = localStorage.getItem('checkWallet');
      sessionStorage.setItem('checkWalletByChain', bychain.toUpperCase());
      if (!Number(checkWallet)) {
        this.$emit('listenWalletPermission', true);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },
    // 下单成功刷新订单
    handleChange() {
      const dataMarket = {
        activeType: 2,
        pairId: '',
        type: '',
        queryMonths: '', // 查询时间：1-近一个月；3-近三个月
        coinCode: '',
      }
      Bus.$emit('handleChange', dataMarket);
    },
    // 服务状态
    handleServerStatus(obj) {
      return new Promise((resolve, reject) => {
        bitModel.swapServerStartus(obj, (res) => {
          if (res && res.rows && res.rows.length > 0) {
            let status = 1;
            if (obj.symbolStatus) {
              const rows = res.rows;
              const item = rows.find(v => v.pair_id === this.checked.pair_id);
              if (item) {
                status = item.status;
              }
            } else {
              status = Number(res.rows[0].value);
            }
            resolve(status); // 服务暂停
            return;
          }
          this.chuLoading = false;
          this.quLoading = false;
          reject('gggg');
          this.$message.error(this.$t('swap.s63'));
        })
      })
    },
    // 获取图标
    handleLogo(item) {
      if (item.symbol === 'EOS/EOSDT' || item.symbol === 'EOS/USN' || item.symbol === 'EOS/USDT') {
        return item.symbol2_logo;
      }
      return item.symbol1_logo;
    }
  },
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.Market {
  .btn-color-green {
    background: #32AF8D;
    border-color: #32AF8D;
  }

  .btn-color-red {
    background: #EA573C;
    border-color: #EA573C;
  }

  .main {
    padding: 30px;
    background: #fff;
    margin-bottom: 25px;

    .changeCaption {
      text-align: right;
      width: 130px;
      padding-right: 15px;
    }

    .cont {
      position: relative;
      min-height: 100px;
      align-items: end;
      background: #F4F9FC;
      padding: 35px 0 35px 0;
      border-radius: 5px;

      & > div {
        flex: 1;
        width: 50%;

        &:nth-child(1) {
          // padding-right: 70px;
        }

        &:nth-child(2) {
          // padding-left: 50px;
        }

        .balance {
          padding-right: 10px;
          color: #999;
          font-size: 12px;
        }

        .btnLeft, .btnRight {
          width: 100% !important;
          margin-top: 20px;
        }

        .btnLeft {
          margin-top: 80px;
        }

        .jt {
          // margin: 20px 0;
          margin: 20px auto 20px;
          transform: rotate(90deg);
          width: 29px;

          .iconOuter {
            border-radius: 50%;
            padding: 5px;
            background: #fff;
            border: 1px solid #4A90E2;

            i {
              color: #4A90E2;
            }
          }
        }
      }

      .centIcon {
        position: absolute;
        top: 10%;
        left: 50%;
        width: 1px;
        height: 300px;
        background: #E7E7E7;
        cursor: pointer;
      }

      .leftItem {
        padding-top: 10px;
        width: 130px;
        align-self: end;
        margin-right: 10px;
        text-align: right;
        padding-right: 15px;

        .canRetrieve {
          margin-top: 97px;
        }
      }

      .rightItem {
        width: 370px;
      }

      .contLeft {
      }

      .contRight {
        .formList {
          margin-right: 20px;
        }
      }
    }

    .nowPrice {
      margin-top: 20px;
      padding: 10px 10px;
      // background: #f4f4f4;
      .nowPriceItem {
        flex: 1;
        margin-right: 50px;

        div:nth-child(1) {
          color: #999;
          margin-bottom: 10px;
        }
        &:nth-child(1) {
          flex: 0.8;
        }
      }
    }

    .btn {
      width: 100%;
      margin-top: 10px;
    }

    /deep/ .el-input-group__prepend {
      // background: #f5f7fa;
      padding: 0 15px;
    }

    /deep/ .el-input-group__prepend .slotCls span {
      width: 53px;
      overflow: hidden;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 53px;
      display: inline-block;
    }
  }

  /deep/ .el-form-item {
    margin-bottom: 10px;
  }
  .slotCls {
    img {
      position: relative;
      display: block;
      margin-right: 5px;
      width: 20px;

      &::before {
        position: absolute;
        top: -10px;
        left: 0;
        content: '';
        display: block;
        width: 20px;
        height: 20px;
        background: url('https://ndi.340wan.com/eos/eosio.token-eos.png') no-repeat;
        background-size: 100% 100%;
      }
    }
  }

  .selectClass {
    position: relative;
    width: 160px;
    /deep/ .el-input__inner {
      padding-left: 50px;
    }
    .slotClass {
      width: 140px;
      line-height: 38px;
      height: 38px;
      position: absolute;
      top: 1px;
      left: 0;
      color: #333;
      padding-left: 15px;

      .checkAreaImg {
        position: relative;
        display: block;
        width: 25px;
        height: 25px;

        &::before {
          position: absolute;
          top: 0;
          left: 0;
          content: '';
          display: block;
          width: 25px;
          height: 25px;
          background: url('https://ndi.340wan.com/eos/eosio.token-eos.png') no-repeat;
          background-size: 100% 100%;
        }
      }
    }
  }

  /deep/ .el-input.is-disabled .el-input__inner {
    background-color: #F6F6F6;
  }

  /deep/ .el-input .el-input-group__prepend {
    background-color: #F6F6F6;
  }
}
.theme-1B1D27 {
  .Market {
    /deep/ .el-input.is-disabled .el-input__inner {
      background-color: $-black1 !important;
    }

    /deep/ .el-input .el-input-group__prepend {
      background-color: $-black1 !important;
    }
  }

  .balance {
    color: $-opacity8 !important;
  }

  .main, .centIcon {
    background: $-black2 !important;
  }

  /deep/ .input-with-select .el-input-group__prepend {
    background: $-black1 !important;
  }

  .nowPrice, .cont {
    background: $-black1 !important;
  }

  .nowPriceItem {
    div:nth-child(1) {
      color: $-opacity8 !important;
    }
  }
}
</style>

